﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using X = Adjunct.Framework.Nuspec.XNames.Package.Metadata.References;

namespace Adjunct.Framework.Nuspec
{
	/// <summary>
	/// 
	/// </summary>
	/// <remarks></remarks>
	public class NuspecLibReferences : List<NuspecLibReference>
	{
		/// <summary>
		/// Clones this instance.
		/// </summary>
		/// <returns></returns>
		/// <remarks></remarks>
		public NuspecLibReferences Clone()
		{
			NuspecLibReferences clone = new NuspecLibReferences();
			clone.AddRange(this.Select(reference => reference.Clone()));
			return clone;
		}

		/// <summary>
		/// Performs an explicit conversion from <see cref="NuspecLibReferences"/> to
		/// <see cref="System.Xml.Linq.XElement"/>.
		/// </summary>
		/// <param name="references">The references.</param>
		/// <returns>Returns null if the references are null or empty for sparse xml.</returns>
		/// <remarks></remarks>
		public static explicit operator XElement(NuspecLibReferences references)
		{
			if ((references == null) || (references.Count == 0))
			{
				return null;
			}
			return new XElement(X.ElementName, references.OrderBy(r => r.Filename).Select(r => (XElement)r));
		}

		/// <summary>
		/// Performs an explicit conversion from <see cref="System.Xml.Linq.XElement"/> to
		/// <see cref="NuspecLibReferences"/>.
		/// </summary>
		/// <param name="element">The element.</param>
		/// <returns>Always returns an instance so that the consumer doesn't have to see if one was created.</returns>
		/// <remarks></remarks>
		public static explicit operator NuspecLibReferences(XElement element)
		{
			NuspecLibReferences references = new NuspecLibReferences();
			if (element != null)
			{
				element.EnsureElementNameIs(X.ElementName);
				references.AddRange(element.Elements(X.Reference.ElementName).Select(child => (NuspecLibReference)child));
			}
			return references;
		}
	}
}